import axios from 'axios'
import { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { refresh_token } from './api'
let huoqutoken = async () => {
	let data : any = await refresh_token({})
	// console.log(data);
	return data
}


// 创建axios实例
const api = axios.create({
	baseURL: 'http://localhost:3000',
	// baseURL: 'http://192.168.1.14:3000',
	timeout: 100000
})

// 请求拦截器
api.interceptors
api.interceptors.request.use((config : AxiosRequestConfig) : any => {
	const headers = config.headers || {}
	let access_token = localStorage.getItem('access_token');
	let REFRESH_token = localStorage.getItem('REFRESH_token');
	headers['Authorization'] = `short+${access_token} length+${REFRESH_token}`;
	config.headers = headers;
	return config;
}, (error : AxiosError) => {
	return Promise.reject(error)
}
)

// 响应拦截器
api.interceptors.response.use((response : AxiosResponse) => {
	if (response.data.code === 1001) {
		alert('没有携带token，请检查')
	} else if (response.data.code === 1002) {
		// alert('短token过期，请重新获取')
		console.log(111);
		huoqutoken()
	} else if (response.data.code === 1003) {
		alert('没有携带长token')
	} else if (response.data.code === 1004) {
		alert('长token过期，请重新登录')
		// 路由跳转
		uni.navigateTo({
			url: '/pages/Login/Login'
		})
	} else if (response.data.code === 2000) {
		localStorage.setItem('access_token', response.data.access_token)
	}
	return response;
},
	(error : AxiosError) => {
		return Promise.reject(error)
	}
)


export default api